package com.baosight.risk.common.pdf.service;

import com.baosight.risk.common.pdf.dto.Office2PdfDto;
import com.baosight.risk.common.pdf.dto.Office2PdfResult;
import com.baosight.risk.common.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author bazhandao
 * @description Office文件(Word / Excel / PPT)转pdf服务接口
 * @date 2019/7/18 14:06
 * @since JDK1.8
 */
@Slf4j
@Service(value = "office2PdfService")
public class Office2PdfServiceImpl implements Office2PdfService {

    private static final HttpClient client = HttpClients.createDefault();

    @Value("${office.2.pdf.server}")
    private String office2PdfServer;


    /**
     * Office文件(Word/Excel/PPT)转pdf
     *
     * @param file
     * @return Office2PdfDto
     * @author bazhandao
     * @date 2019－07－18
     */
    @Override
    public Office2PdfDto office2Pdf(File file) {
        //检查文件类型是否正确
        check(file);
        try {
            HttpPost post = new HttpPost(office2PdfServer + "/upload");
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addBinaryBody("file", file);
            multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            post.setEntity(httpEntity);
            HttpResponse httpResponse = client.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String content = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                Office2PdfResult result = JSONUtils.unmarshal(content, Office2PdfResult.class);
                if (result.getCode() == 1) {
                    return result.getData();
                }
            }
        } catch (Exception e) {
            log.error("文件转换为pdf失败,{},{}", file.getPath(), e);
        }
        return null;
    }

    /**
     * Office文件(Word/Excel/PPT)转pdf，返回pdf文件字节
     *
     * @param file
     * @return Office2PdfDto
     * @author bazhandao
     * @date 2019－07－18
     */
    @Override
    public byte[] office2PdfByte(File file) {
        Office2PdfDto dto = office2Pdf(file);
        String url = dto.getPdfFileUrl();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                entity.writeTo(baos);
                return baos.toByteArray();
            }
        } catch (Exception e) {
            log.error("Office转pdf文件byte数组,出错!!!", e);
        }
        return null;
    }

    /**
     * 检查文件是否符合word/excel/ppt文件类型
     *
     * @param file
     * @return
     * @author bazhandao
     * @date 2019-07-18
     */
    private boolean check(File file) {
        if (!file.exists()) {
            throw new RuntimeException("文件不存在,file=" + file.getPath());
        }
        String fileName = file.getName().toLowerCase();
        int dot = fileName.lastIndexOf('.');
        fileName = fileName.substring(dot);
        if (fileName.equals(".doc")
                || fileName.equals(".docx")
                || fileName.equals(".xls")
                || fileName.equals(".xlsx")
                || fileName.equals(".ppt")
                || fileName.equals(".pptx")) {
            return true;
        }
        throw new RuntimeException("不支持的文件类型,仅支持.doc、.docx、.xls、.xlsx、.ppt、.pptx类型的文件file=" + file.getPath());
    }
}
